package com.xiaoyu.lanling.app

import `in`.srain.cube.request.JsonData
import `in`.srain.cube.util.general.GeneralUtil
import com.tencent.bugly.crashreport.CrashReport
import com.xiaoyu.base.AppDatabase
import com.xiaoyu.base.data.UserData
import com.xiaoyu.im.client.IMClient
import com.xiaoyu.im.provider.ChatIdMapper
import com.xiaoyu.im.provider.ConversationManager
import com.xiaoyu.im.provider.MessageReceiptData
import com.xiaoyu.lanling.data.AppStateData
import com.xiaoyu.lanling.feature.voicecall.data.CallData
import com.xiaoyu.lanling.feature.voicecall.listener.CallLifecycleListener
import com.xiaoyu.lanling.feature.newtips.data.NewTipData
import com.xiaoyu.lib_av.manager.AgoraManager
import com.xiaoyu.lib_av.manager.CallManager

object AppHelper {

    fun afterLogout(runnable: Runnable? = null) {
        val uid = UserData.getInstance().uid
        GeneralUtil.runFromBackgroundToMain({
            ConversationManager.getInstance().clear()
            ChatIdMapper.getInstance().clear()
            MessageReceiptData.getInstance().clear()
            NewTipData.instance.clear()
            CrashReport.setUserId("")
            AgoraManager.getInstance().logout()
            IMClient.getInstance().logout()
            AppDatabase.closeDatabase(uid)
            UserData.getInstance().afterLogout()
        }, runnable)
    }

    fun afterLogin(jsonData: JsonData) {
        UserData.getInstance().afterLogin(jsonData)
        AppStateData.instance.onAppStartOrLogin()
        IMClient.getInstance().login()
        CallManager.instance.init(CallLifecycleListener.instance)
        AgoraManager.getInstance().login(CallData.sLoginRunnable)
        CrashReport.setUserId(UserData.getInstance().uid)
        NewTipData.instance.reload()
        ConversationManager.getInstance().loadConversationListFromDBAsync()
    }
}